<?php
namespace app\modules\supplier\logic;
use app\modules\base\LogicBase;
use think\Db;
use app\modules\supplier\traits\ParseShopGoods;
/**
 *
 */

class ShopGoodsLogic extends LogicBase
{
use ParseShopGoods;
    public function _initialize()
    {

    }

    /**
     * 商品列表all
     * @param array $_option 数组
     * @return bool|array
     */

    public function index($_option=[]){
        $option = [
            'is_pages' => false,//是否分页查询
            'page_current' => 10,//分页查询时，当前页码
            'page_size' => 1,
            'keyword' => '',
            'order' => 'DESC',
            'sort' => 'G.create_time'
        ];

        if (is_array($_option)) {
            if (isset($_option['is_pages'])) {
                $option['is_pages'] = $_option['is_pages'] ? true : false;
            }
            if (isset($_option['page_current'])) {
                $option['page_current'] = intval($_option['page_current']);
                $option['page_current'] = $option['page_current'] < 1 ? 1 : $option['page_current'];
            }
            if (isset($_option['page_size'])) {
                $option['page_size'] = intval($_option['page_size']);
                $option['page_size'] = $option['page_size'] < 1 ? 1 : $option['page_size'];
            }
            if (isset($_option['field'])) {
                $option['field'] = strip_tags(trim($_option['field']));
                $option['field'] = $option['field'] == 'all' ? '*' : $option['field'];
            }

            if (isset($_option['sort'])) {
                $option['sort'] = strip_tags(trim($_option['sort']));
                if (empty($option['sort'])) {
                    $option['sort'] = "G.create_time";
                }
            }
            if (isset($_option['order'])) {
                $option['order'] = strip_tags(trim($_option['order']));
            }

            //筛选条件
            if (isset($_option['keyword'])) {
                $option['keyword'] = strip_tags(trim($_option['keyword']));
            }

            if (isset($_option['cate_id'])){
                $option['cate_id'] = intval($_option['cate_id']);
            }
        }

        $where =[];

        if(!empty($option['cate_id'])){
            $where['G.category_id'] = $option['cate_id'];
        }

        if (!empty($option['keyword'])){
            $where['G.goods_name|GB.brand_name|GC.cate_name'] = ['like', '%' . str_replace('%', '\%', $option['keyword']) . '%'];
        }

        if ($option['is_pages']) {
            $data['record_count'] = Db::name('goods')->alias('G')
                ->join('goods_brand GB','G.brand_id = GB.brand_id','LEFT')
                ->join('goods_category GC','G.category_id = GC.cate_id','LEFT')
                ->where($where)
                ->count();
            $data['page_size'] = $option['page_size'];
            $data['page_max'] = ceil($data['record_count'] / $option['page_size']);
            $data['page_current'] = $option['page_current'];
            $data['list'] =  Db::name('goods')->alias('G')
                ->join('goods_brand GB','G.brand_id = GB.brand_id','LEFT')
                ->join('goods_category GC','G.category_id = GC.cate_id','LEFT')
                ->where($where)
                ->order($option['sort'].' '.$option['order'])
                ->page($option['page_current'], $option['page_size'])->
                select();
        }else{
            $data['record_count'] = Db::name('goods')->alias('G')
                ->join('goods_brand GB','G.brand_id = GB.brand_id','LEFT')
                ->join('goods_category GC','G.category_id = GC.cate_id','LEFT')
                ->where($where)
                ->count();
            $data['page_size'] = $option['page_size'];
            $data['page_max'] = ceil($data['record_count'] / $option['page_size']);
            $data['page_current'] = $option['page_current'];
            $data['list'] =  Db::name('goods')->alias('G')
                ->join('goods_brand GB','G.brand_id = GB.brand_id','LEFT')
                ->join('goods_category GC','G.category_id = GC.cate_id','LEFT')
                ->where($where)
                ->order($option['sort'].' '.$option['order'])
                ->limit($option['page_size'])
                ->select();
        }

        foreach ($data['list'] as $key => $val){
            $data['list'][$key] =  $this->_parseShopGoods($val);
            //获取商品规格基础数据
            $data['list'][$key]['goods_specval'] = Db::name('goods_specval')->alias('GS')
                ->join('goods_spec GP','GS.spec_id = GP.spec_id','LEFT')
                ->where(['GS.goods_id'=>$val['goods_id'],'GS.specval_pid'=>0,'GS.status'=>1])
                ->select();

        }

//        echo Db::name('goods')->getLastSql();exit();

        return $data;

    }

    /**
     * 商品列表my
     * @param int   $supplier_id 供应商ID
     * @param array $_option 数组
     * @return bool|array
     */

    public function myIndex($supplier_id,$_option=[]){
        if (empty($supplier_id) || !Db::name('supplier')->where(['supplier_id'=>$supplier_id])->find() ){
            $this->_error[] ='无效参数';
            return false;
        }

        $option = [
            'is_pages' => false,//是否分页查询
            'page_current' => 10,//分页查询时，当前页码
            'page_size' => 1,
            'keyword' => '',
            'order' => 'DESC',
            'sort' => 'G.create_time'
        ];

        if (is_array($_option)) {
            if (isset($_option['is_pages'])) {
                $option['is_pages'] = $_option['is_pages'] ? true : false;
            }
            if (isset($_option['page_current'])) {
                $option['page_current'] = intval($_option['page_current']);
                $option['page_current'] = $option['page_current'] < 1 ? 1 : $option['page_current'];
            }
            if (isset($_option['page_size'])) {
                $option['page_size'] = intval($_option['page_size']);
                $option['page_size'] = $option['page_size'] < 1 ? 1 : $option['page_size'];
            }
            if (isset($_option['field'])) {
                $option['field'] = strip_tags(trim($_option['field']));
                $option['field'] = $option['field'] == 'all' ? '*' : $option['field'];
            }

            if (isset($_option['sort'])) {
                $option['sort'] = strip_tags(trim($_option['sort']));
                if (empty($option['sort'])) {
                    $option['sort'] = "G.create_time";
                }
            }
            if (isset($_option['order'])) {
                $option['order'] = strip_tags(trim($_option['order']));
            }

            //筛选条件
            if (isset($_option['keyword'])) {
                $option['keyword'] = strip_tags(trim($_option['keyword']));
            }

            if (isset($_option['cate_id'])){
                $option['cate_id'] = intval($_option['cate_id']);
            }
        }

        //初始化条件 供应商上架
        $goods_id = Db::name('goods_specval')->where(['supplier_id'=>$supplier_id])->group('goods_id')->column('goods_id');
        //为空的情况
        if (empty($goods_id)){
            $goods_id = 0;
        }

        $where =['G.goods_id'=>['IN',$goods_id]];

        if(!empty($option['cate_id'])){
            $where['G.category_id'] = $option['cate_id'];
        }

        if (!empty($option['keyword'])){
            $where['G.goods_name|GB.brand_name|GC.cate_name'] = ['like', '%' . str_replace('%', '\%', $option['keyword']) . '%'];
        }


        if ($option['is_pages']) {

            $data['record_count'] = Db::name('goods')->alias('G')
                ->join('goods_brand GB','G.brand_id = GB.brand_id','LEFT')
                ->join('goods_category GC','G.category_id = GC.cate_id','LEFT')
                ->where($where)
                ->count();
            $data['page_size'] = $option['page_size'];
            $data['page_max'] = ceil($data['record_count'] / $option['page_size']);
            $data['page_current'] = $option['page_current'];
            $data['list'] =  Db::name('goods')->alias('G')
                ->join('goods_brand GB','G.brand_id = GB.brand_id','LEFT')
                ->join('goods_category GC','G.category_id = GC.cate_id','LEFT')
                ->where($where)
                ->order($option['sort'].' '.$option['order'])
                ->page($option['page_current'], $option['page_size'])
                ->select();
        }else{
            $data['record_count'] = Db::name('goods')->alias('G')
                ->join('goods_brand GB','G.brand_id = GB.brand_id','LEFT')
                ->join('goods_category GC','G.category_id = GC.cate_id','LEFT')
                ->where($where)
                ->count();
            $data['page_size'] = $option['page_size'];
            $data['page_max'] = ceil($data['record_count'] / $option['page_size']);
            $data['page_current'] = $option['page_current'];
            $data['list'] =  Db::name('goods')->alias('G')
                ->join('goods_brand GB','G.brand_id = GB.brand_id','LEFT')
                ->join('goods_category GC','G.category_id = GC.cate_id','LEFT')
                ->where($where)
                ->order($option['sort'].' '.$option['order'])
                ->limit($option['page_size'])
                ->select();
        }

        foreach ($data['list'] as $key => $val){
            $data['list'][$key] =  $this->_parseShopGoods($val);
            //获取商品规格基础数据
            $data['list'][$key]['goods_specval'] = Db::name('goods_specval')->alias('GS')
                ->join('goods_spec GP','GS.spec_id = GP.spec_id','LEFT')
                ->where(['GS.goods_id'=>$val['goods_id'],'GS.specval_pid'=>['<>',0],'GS.status'=>1,'GS.supplier_id'=>$supplier_id])
                ->select();

        }


        return $data;

    }

    /**
     * 商品详情all
     * @param integer $goods_id 商品ID
     * @return bool|array
     */
    public function getGoods($goods_id = 0){
        if (empty($goods_id) || !Db::name('goods')->where(['goods_id'=>$goods_id])->find()){
            $this->_error[] ='无效参数';
            return false;
        }
        $where =['goods_id'=>$goods_id];
        //商品详情数据
        $data['goods'] = Db::name('goods')->alias('G')
            ->join('goods_brand GB','G.brand_id = GB.brand_id','LEFT')
            ->join('goods_category GC','G.category_id = GC.cate_id','LEFT')
            ->where($where)
            ->find();

        $data['goods'] = $this->_parseShopGoods($data['goods']);

        //获取商品规格基础数据
        $data['goods_specval'] = Db::name('goods_specval')->alias('GS')
            ->join('goods_spec GP','GS.spec_id = GP.spec_id','LEFT')
            ->where(['GS.goods_id'=>$data['goods']['goods_id'],'GS.specval_pid'=>0,'GS.status'=>1])
            ->select();

        return $data;

    }

    /**
     * 商品详情my
     * @param integer $supplier_id 供应商ID
     * @param integer $goods_id 商品ID
     * @return bool|array
     */
    public function getMyGoods($supplier_id = 0,$goods_id = 0){

        if (empty($supplier_id) || !Db::name('supplier')->where(['supplier_id'=>$supplier_id])->find() ){
            $this->_error[] ='无效参数';
            return false;
        }

        if (empty($goods_id) || !Db::name('goods')->where(['goods_id'=>$goods_id])->find()){
            $this->_error[] ='无效参数';
            return false;
        }
        $where =['goods_id'=>$goods_id];
        //商品详情数据
        $data['goods'] = Db::name('goods')->alias('G')
            ->join('goods_brand GB','G.brand_id = GB.brand_id','LEFT')
            ->join('goods_category GC','G.category_id = GC.cate_id','LEFT')
            ->where($where)
            ->find();

        $data['goods'] = $this->_parseShopGoods($data['goods']);

        //获取商品规格基础数据
        $data['goods_specval'] = Db::name('goods_specval')->alias('GS')
            ->join('goods_spec GP','GS.spec_id = GP.spec_id','LEFT')
            ->where(['GS.goods_id'=>$data['goods']['goods_id'],'GS.specval_pid'=>['<>',0],'GS.status'=>1,'supplier_id'=>$supplier_id])
            ->select();

        return $data;

    }

    /**
     * 添加商品规格
     * @param array $data 参数
     * @return bool|array
     */
    public function addGoodsSpes($data = []){
            if (empty($data['supplier_id']) || !Db::name('supplier')->where(['supplier_id'=>$data['supplier_id']])->find()){
                 $this->_error[] = '无效参数';
                 return false;
            }

            Db::startTrans();//开启事务
            $res = false;
            if (is_array($data['data']) && !empty($data['data'])){
              foreach ($data['data'] as $key => $val){
                  //隐藏域数据  specval_id 为了避免数据更新 再次查询后查入
                  $insertData = Db::name('goods_specval')->where(['specval_id'=>$val['specval_id']])->find();
                      if (empty($insertData)){
                          $this->_error[] ='第【'.($key+1).'】个规格不存在！';
                          return false;
                      }

                     $insertData['specval_pid'] = $insertData['specval_id']; //强制更新字段
                     unset($insertData['specval_id']);

                     if (empty($insertData['goods_id']) || !Db::name('goods')->where(['goods_id'=>$insertData['goods_id']])->find() ){
                          $this->_error[]='产品不存在！';
                          return false;
                     }

                  //系统会话数据
                     $insertData['supplier_id'] = $data['supplier_id'];

                  //真实提交的数据
                     $insertData['price'] = $val['price'];
                     if (empty($insertData['price'])){
                         $this->_error[]='请填写规格【'.$insertData['specval_name'].'】价格！';
                         return false;
                     }
                     //监测价格
                     if (!is_numeric($insertData['price'])){
                         $this->_error[]='规格【'.$insertData['specval_name'].'】价格,请填写正确的格式';
                         return false;
                     }
                     $insertData['unit_price'] =!empty($insertData['specvalnum'])?round(($insertData['price']/$insertData['specvalnum']),2):0;
                     $insertData['status'] = $val['status'];

                     //监测上下架状态 下架状态跳出循环 继续下次循环
                     if (!$insertData['status']){
                             continue;
                     }

                     $insertData['create_date'] = date('Y-m-d H:i:s');
                     $insertData['update_date'] = date('Y-m-d H:i:s');

                     if(Db::name('goods_specval')->where(['specval_pid'=>$insertData['specval_pid'],'specval_name'=>$insertData['specval_name'],'supplier_id'=>$insertData['supplier_id']])->find() ){
                         $this->_error[] ='您已经上架该规格【'.$insertData['specval_name'].'】，请勿重复上架！';
                         return false;
                     }

                     $res = Db::name('goods_specval')->insert($insertData);
              }

              if ($res){
                  Db::commit();
                  return true;
              }else{
                  Db::rollback();
                  $this->_error[] = '上架失败';
                  return false;
              }
            }else{
                $this->_error[] ='无供应商规格添加';
                return false;
            }

    }


    /**
     * 添加商品规格
     * @param array $data 参数
     * @return bool|array
     */
    public function editGoodsSpes($data = []){


        Db::startTrans();//开启事务
        $res = false;

        if (is_array($data) && !empty($data)){
            foreach ($data as $key => $val){
                //隐藏域数据  需要隐藏域 specval_id
                $specval_id = $val['specval_id'];

                if (empty($specval_id) || !Db::name('goods_specval')->where(['specval_id'=>$specval_id])->find() ){
                    $this->_error[] ='第【'.($key+1).'】个规格不存在！';
                    return false;
                }

                $info =  Db::name('goods_specval')->where(['specval_id'=>$specval_id])->find();

                //强制验证
                if (empty($info['specval_pid'] || !Db::name('goods_specval')->where(['specval_id'=>$info['specval_pid']])->find() )){
                    $this->_error[] ='第【'.($key+1).'】个规格不存在！';
                    return false;
                }

                if (empty($info['goods_id']) || !Db::name('goods')->where(['goods_id'=>$info['goods_id']])->find() ){
                    $this->_error[]='产品不存在！';
                    return false;
                }

                //系统会话数据
                if (empty($info['supplier_id']) || !Db::name('supplier')->where(['supplier_id'=>$info['supplier_id']])->find()){
                    $this->_error[] = '供应商不存在！';
                    return false;
                }

                //真实提交的数据
                $updateData['price'] = $val['price'];
                if (empty($updateData['price'])){
                    $this->_error[]='请填写规格【'.$info['specval_name'].'】价格！';
                    return false;
                }
                //监测价格
                if (!is_numeric($updateData['price'])){
                    $this->_error[]='规格【'.$info['specval_name'].'】价格,请填写正确的格式';
                    return false;
                }

                $updateData['unit_price'] = !empty($info['specvalnum'])?round(($updateData['price']/$info['specvalnum']),2):0;

                $updateData['status'] = $val['status'];
                $updateData['update_date'] = date('Y-m-d H:i:s');

                $res = Db::name('goods_specval')->where(['specval_id'=>$specval_id])->update($updateData);
            }

            if ($res!==false){
                Db::commit();
                return true;
            }else{
                Db::rollback();
                $this->_error[] = '更新失败';
                return false;
            }
        }else{
            $this->_error[]='无供应商规格添加';
            return false;
        }

    }

    /**
     * 删除商品规格 all
     * @param array $data 参数
     * @return bool|array
     */
    public function delGoodsSpes($data =[]){
           if (empty($data['supplier_id']) || !Db::name('supplier')->where(['supplier_id'=>$data['supplier_id']])->find() ){
               $this->_error[]='供应商不存在！';
               return false;
           }

           if (empty($data['goods_id']) || !Db::name('goods')->where(['goods_id'=>$data['goods_id']])->find() ){
               $this->_error[]='商品不存在！';
               return false;
           }

           if ( !Db::name('goods_specval')->where(['supplier_id'=>$data['supplier_id'],'goods_id'=>$data['goods_id'],'specval_pid'=>['<>',0]])->select() ){
                $this->_error[] = '此商品供应商提供规格不存在！';
                return false;
           }

           $res = Db::name('goods_specval')->where(['supplier_id'=>$data['supplier_id'],'goods_id'=>$data['goods_id'],'specval_pid'=>['<>',0]])->delete();

           if ($res){
               return true;
           }else{
               return false;
           }

    }

    /**
     * 删除商品规格 all
     * @param array $data 参数
     * @return bool|array
     */
    public function delGoodsSpesOne($data =[]){
        if (empty($data['supplier_id']) || !Db::name('supplier')->where(['supplier_id'=>$data['supplier_id']])->find() ){
            $this->_error[]='供应商不存在！';
            return false;
        }

        if ( !Db::name('goods_specval')->where(['supplier_id'=>$data['supplier_id'],'specval_id'=>$data['specval_id'],'specval_pid'=>['<>',0]])->find() ){
            $this->_error[] = '此规格不存在！';
            return false;
        }

        $goods_id  = Db::name('goods_specval')->where(['specval_id'=>$data['specval_id'],'supplier_id'=>$data['supplier_id']])->value('goods_id');
//        echo Db::name('goods_specval')->getLastSql();
//        dump($goods_id);exit();

        if (empty($goods_id) || !Db::name('goods')->where(['goods_id'=>$goods_id])->find() ){
            $this->_error[]='商品不存在！';
            return false;
        }

        $res = Db::name('goods_specval')->where(['supplier_id'=>$data['supplier_id'],'specval_id'=>$data['specval_id'],'specval_pid'=>['<>',0]])->delete();

        if ($res){
            return true;
        }else{
            return false;
        }

    }

    /**
     * 商品分类
     * @param array $cate_id 参数
     * @return bool|array
     */

    public function getCate($cate_id = 0){
        $where = ['cate_status'=>1];//开启状态
        if (empty($cate_id)){ //一级分类
            $where['cate_pid']= 0;
        }else{
            $where['cate_pid'] = $cate_id;
        }

        $data = Db::name('goods_category')->field('cate_id,cate_name,cate_pid')->where($where)->order('listorder ASC')->select();

//          echo Db::name('goods_category')->getLastSql();exit();

        return $data;

    }

    /**
     * 商品包装
     * @param array $cate_id 参数
     * @return bool|array
     */

    public function getSpec(){

        $data = Db::name('goods_spec')->where(['spec_status'=>1])->select();
//          echo Db::name('goods_category')->getLastSql();exit();
        return $data;

    }

}